//
//  AppDelegate.m
//  TuYouAPP
//
//  Created by L on 14-2-18.
//
//

#import "AppDelegate.h"
#import "MainLinesVC.h"
#import <MAMapKit/MAMapKit.h>
#import "MTA.h"
#import <AVOSCloud/AVOSCloud.h>
#import "Util.h"
#import "DataModel.h"
#import <AVOSCloudSNS/AVOSCloudSNS.h>
#import <ShareSDK/ShareSDK.h>
#import "WeiboApi.h"
#import "WXApi.h"
#import <AVOSCloudSNS/AVOSCloudSNS.h>
#import "QiniuSimpleUploader.h"
#import "MySelfInfoVC.h"


@implementation AppDelegate
- (void)initializePlat
{
    
    
     [ShareSDK registerApp:@"1499802f2b7b"];
    
    [ShareSDK connectSinaWeiboWithAppKey:@"343058692"
                               appSecret:@"2e6e16af4995daae8bb9dec829acde48"
                             redirectUri:@"http://www.tuyou.com"];
//    /**
//     连接腾讯微博开放平台应用以使用相关功能，此应用需要引用TencentWeiboConnection.framework
//     http://dev.t.qq.com上注册腾讯微博开放平台应用，并将相关信息填写到以下字段
//     
//     如果需要实现SSO，需要导入libWeiboSDK.a，并引入WBApi.h，将WBApi类型传入接口
//     **/
    [ShareSDK connectTencentWeiboWithAppKey:@"801482970"
                                  appSecret:@"0dc1d53fe6283cd294d7285c4ae89270"
                                redirectUri:@"http://www.tuyou.com"
                                   wbApiCls:[WeiboApi class]];
    
    [ShareSDK connectWeChatWithAppId:@"wxdf2253ef66c13e08" wechatCls:[WXApi class]];


}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"deviceToken get ok");
    AVUser* user = [AVUser currentUser];
    
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    
    if( user )
    {
        [currentInstallation setObject:user.objectId forKey:@"userojid"];
    }
    [currentInstallation setDeviceTokenFromData:deviceToken];
    [currentInstallation addUniqueObject:@"public_ch" forKey:@"channels"];//关注公共频道
    [currentInstallation saveInBackground];
    
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
     NSLog(@"pushRegistFail Error: %@", err);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

//    NSString* v = @"Voicemail.caf";
//    
//    if( v )
//    {
//        NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@",v];
//        
//        SystemSoundID sound;
//        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
//        AudioServicesPlaySystemSound(sound);
        
//        //通知到线路页面
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushmsg" object:nil];
//    }

    [self initializePlat];
    [MAMapServices sharedServices].apiKey = MapAPIKey;
    [MTA startWithAppkey:@"IDKC9HZ153BB"];
    [AVOSCloud setApplicationId:@"j04k850g6jhcza9h6kvz3x9jhuq9xim93ddno1ib7tr6ucit" clientKey:@"5bvty3ylcuj6pjufex6wqig3vyxqgsimo5lzohcgykepij63"];

   [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];

//    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
//    [currentInstallation addUniqueObject:@"Giants" forKey:@"channels"];
//    [currentInstallation saveInBackground];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    MainLinesVC *vc = [[MainLinesVC alloc]init];

    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:vc];

    self.window.rootViewController = navc;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [self createUUIDUser];
    
    [self dealNotfi: launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
    
    return YES;
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [self dealBadge];
    [TYUser currentUser].mbchanged = YES;
    //显示起泡
    //NSLog(@"didReceiveRemoteNotification:%@",userInfo);

    GotoPage g = [[userInfo objectForKey:@"Ntype"] intValue];
    if ( g == E_ReBackMe || g == E_ReBackMyStatus )
    {
//        SystemSoundID systemSoundId;
//        OSStatus status;
//        
//        status = AudioServicesCreateSystemSoundID((CFURLRef) CFBridgingRetain([[NSBundle mainBundle] URLForResource: @"Voicemail" withExtension: @"caf"]),
//                                                  &systemSoundId);
//        if (status != noErr) {
//            NSLog(@"Cannot create sound: %d", (int)status);
//        }
//         AudioServicesPlaySystemSound(1031);
//        //通知到线路页面
      //  [[NSNotificationCenter defaultCenter] postNotificationName:@"pushmsg" object:nil];
        
        [self updateBadge];
    
    }
    [AVPush handlePush:userInfo];
    
}
-(void)updateBadge
{
    [[TYUser currentUser] getAllNotDealCount:^(NSInteger count, NSString *eror) {
        
        
        AVInstallation *currentInstallation = [AVInstallation currentInstallation];
        if( currentInstallation )
        {
            [currentInstallation fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                AVInstallation* ttt = (AVInstallation*)object;
                if( ttt )
                {
                    ttt.badge = count;
                    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: count];
                    [[UIApplication sharedApplication] cancelAllLocalNotifications];
                    // [ttt incrementKey:@"badge" byAmount:[NSNumber numberWithInt:count]];
                    [ttt saveEventually];
                }
            }];
        }
        
        if( count )
            [MainLinesVC shareVC].badgeView.badgeText = [NSString stringWithFormat:@"%d",count];
        else
            [MainLinesVC shareVC].badgeView .badgeText = nil;
    }];
}
-(void)createUUIDUser
{
    if( [AVUser currentUser ] ) return;
    
    AVUser* usera = [AVUser user];
    [usera setObject:[Util GetUUID] forKey:@"username"];
    [usera setObject:@"tuyou_auto_psw" forKey:@"password"];
    
    //直接注册一个新的
    [usera signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
    }];
    
}
//+ (NSString*)getIphoneUDID
//{
//    return [[UIDevice currentDevice]identifierForVendor];
//}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}


-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


-(GotoPage)dealNotfi:(NSDictionary*)notificationPayload
{
    if( notificationPayload )
    {
        [GInfo shareClient].mgoto = [[notificationPayload objectForKey:@"Ntype"] intValue];
        [GInfo shareClient].mojid = [notificationPayload objectForKey:@"SOjid"];
        
        [TYUser currentUser].mbchanged = YES;
    }
    return E_NotGoto;
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [TYUtil updateUserPoint];
}
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    
    NSLog(@"handleOpenURL");
    
    if ([GInfo shareClient].isAVOSCloud == YES) {
        return [AVOSCloudSNS handleOpenURL:url];

    }
    else
    {
        return [ShareSDK handleOpenURL:url
                            wxDelegate:self];
    }
    
}
-(void)dealBadge
{
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    if( [currentInstallation objectForKey:@"userojid"])
    {
        [currentInstallation fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            AVInstallation* ttt = (AVInstallation*)object;
            if( ttt.badge )
            {
              //  [ttt incrementKey:@"badge" byAmount:[NSNumber numberWithInt:-1]];
                if ([AVInstallation currentInstallation].badge==0) {
                    
                }
                else
                {
                    [MainLinesVC shareVC].badgeView.badgeText = [NSString stringWithFormat:@"%d",[AVInstallation currentInstallation].badge];
                }
                [ttt saveEventually];
            }
        }];
    }
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [self dealBadge];
    
    
      //[[NSNotificationCenter defaultCenter]postNotificationName:@"updateBadge" object:nil];
    
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
//    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



@end

